﻿using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using System.Text;
using Neatly.UI;

namespace PandoraEditor.Window
{
    [PdrWindowAbbr("NImage替换工具")]
    public class NImageReplaceWindow : IDrawPanel
    {
        private static string m_OldSpriteName = "";
        private static string m_NewSpriteName = "";

        public override void DrawPanel()
        {
            GUILayout.BeginHorizontal();
            {
                GUILayout.Space(10);
                GUILayout.BeginVertical("box", GUILayout.MaxWidth(300));
                {
                    GUILayout.Space(10);
                    m_OldSpriteName = EditorGUILayout.TextField("旧SpriteName:", m_OldSpriteName).Trim();
                    EditorGUILayout.LabelField("");
                    m_NewSpriteName = EditorGUILayout.TextField("新SpriteName:", m_NewSpriteName).Trim();
                    EditorGUILayout.LabelField("");
                    GUILayout.BeginHorizontal(GUILayout.MaxWidth(150));
                    {
                        if (GUILayout.Button("替换"))
                        {
                            ExecuteReplace();
                        }
                    }
                    GUILayout.EndHorizontal();
                }
                GUILayout.EndVertical();
            }
            GUILayout.EndHorizontal(); //最外层布局
        }

        static void ExecuteReplace()
        {
            Debug.Log("替换完成");
        }

        static void Check(AssetObject assetObject)
        {
            GameObject source = assetObject.gameObject;
            if (GetOldImages(source).Count > 0)
            {
                GameObject newGo = PrefabUtility.InstantiatePrefab(source) as GameObject;
                var imageList = GetOldImages(newGo);
                for (int i = 0; i < imageList.Count; i++)
                {
                    UIUtility.FixImageSprite(imageList[i], m_NewSpriteName, m_OldSpriteName);
                }
                PrefabUtility.ReplacePrefab(newGo, source, ReplacePrefabOptions.ConnectToPrefab);
                Object.DestroyImmediate(newGo);
            }
        }

        static List<NImage> GetOldImages(GameObject go)
        {
            List<NImage> list = new List<NImage>();
            var images = go.GetComponentsInChildren<NImage>(true);
            for (int i = 0; i < images.Length; i++)
            {
                NImage image = images[i];
                if (image.SpriteName == m_OldSpriteName)
                {
                    list.Add(image);
                }
            }
            return list;
        }
    }
}